package cn.kone.system.service.impl;

import cn.kone.system.domain.Role;
import cn.kone.system.mapper.RoleMapper;
import cn.kone.system.query.RoleQuery;
import cn.kone.system.service.IRoleService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 查询单个
     *
     * @param id
     * @return
     */
    @Override
    public Role findOne(Long id) {
        return roleMapper.findOne(id);
    }

    /**
     * 查询全部
     *
     * @return
     */
    @Override
    public List<Role> findAll() {
        return roleMapper.findAll();
    }

    /**
     * 新增单个
     *
     * @param role
     */
    @Override
    public void addRole(Role role) {
        //新增角色信息
        roleMapper.addRole(role);
        //判断Role这个里面有没有权限id
        if (role.getPermissions().size() > 0) {
            roleMapper.addRolePermissions(role);
        }
        //判断Role里有没有菜单id
        if (role.getMenus().size() > 0) {
            roleMapper.addRoleMenus(role);
        }
    }

    /**
     * 修改单个
     *
     * @param role
     */
    @Override
    public void updateRole(Role role) {
        roleMapper.updateRole(role);
        //先删除掉原来的权限,然后再修改
        roleMapper.delPermission(role.getId());
        //先删除掉原来的菜单,然后再修改
        roleMapper.delMenu(role.getId());
        //判断Role这个里面有没有权限id
        if (role.getPermissions().size() > 0) {
            roleMapper.addRolePermissions(role);
        }
        //判断Role里有没有菜单id
        if (role.getMenus().size() > 0) {
            roleMapper.addRoleMenus(role);
        }
    }

    /**
     * 删除单个
     *
     * @param id
     */
    @Override
    public void deleteRole(Long id) {

        //先删除掉原来的权限,然后再修改
        roleMapper.delPermission(id);
        //先删除掉原来的菜单,然后再修改
        roleMapper.delMenu(id);
        //删除角色信息
        roleMapper.deleteRole(id);
    }

    /**
     * 高级查询+分页
     *
     * @param roleQuery
     * @return
     */
    @Override
    public List<Role> pageQuery(RoleQuery roleQuery) {
        PageHelper.startPage(roleQuery.getCurrentPage(), roleQuery.getPageSize());
        return roleMapper.pageQuery(roleQuery);
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void batchDeleteRole(Long[] ids) {
        for (Long id : ids) {
            deleteRole(id);
        }
    }
}
